package com.my.socket.nio.v20;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by ZhongGang
 * at 2018/7/4 17:03
 */
public class AcceptTask implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(AcceptTask.class);

    private Selector acceptSelector;
    private Selector readWriteSelector;

    public AcceptTask(Selector acceptSelector, Selector readWriteSelector) {
        this.acceptSelector = acceptSelector;
        this.readWriteSelector = readWriteSelector;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            try {
                int select = this.acceptSelector.select();
                if (select == 0) {
                    continue;
                }
                LOGGER.info("{} event(s) incoming......", select);

                Set<SelectionKey> selectionKeys = this.acceptSelector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    if (selectionKey.isAcceptable()) {
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        LOGGER.info("incoming socket channel: {}, total connections: {}", socketChannel, ++count);
                        socketChannel.register(this.readWriteSelector, SelectionKey.OP_READ);
                    } else {
                        LOGGER.info("unhandled selection key: {}", selectionKey);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("exception caught, the error is {}", e.getMessage());
            }
        }
    }
}
